import java.sql.Array;
import java.util.*;

public class LeetCode394 {
    public static void main(String[] args) {
        System.out.println(decodeString("3[a]2[bc]"));
    }

    /**
     * 思路：
     * 1.将s的非]字符压入栈中，
     * 2.一旦碰到]字符，则栈pop出来字符串，并保存到temp字符串中，直到碰到[字符，然后将[字符前面的数字num提取出来
     * 3.根据num的大小，将temp复制num次，得到新的字符串temparr，将temparr压入数字之前的栈中（即：数字及之后的[xx]的数据都从栈中弹出）
     * 4.然后继续遍历s数组重复2步骤，直到s数组入栈完毕
     * @param s
     * @return
     */
    public static String decodeString(String s) {
        StringBuilder result = new StringBuilder();

        char[] sArr = s.toCharArray();

        Deque<Character> stack = new ArrayDeque<>();
        for (int i = 0; i < sArr.length; i++){
            char c = sArr[i];
            if(c != ']'){
                stack.push(c);
            }else{
                String temp = "";
                char curr = 0;
                while (!stack.isEmpty() && (curr = stack.pop()) != '['){
                    temp = curr + temp;
                }

                String num = "";
                while (!stack.isEmpty() && ((curr = stack.pop()) >= '0' && curr <= '9')){
                    num = curr + num;
                }
                if(!stack.isEmpty()){
                    stack.push(curr);
                }


                int n = Integer.parseInt(num);
                StringBuilder tempArr = new StringBuilder();
                for (int k = 0; k < n; k++){
                    tempArr.append(temp);
                }

                char[] tempArrChar = tempArr.toString().toCharArray();
                for (char cItem: tempArrChar){
                    stack.push(cItem);
                }
            }
        }

        for (Character c : stack){
            result.append(c);
        }

        return result.reverse().toString();
    }
}
